package com.lry.basic.jvm.asm.transform_class.demo20;

import com.itranswarp.compiler.JavaStringCompiler;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Test2 {
    public static void main(String[] args) throws Exception {
        String code =
                "public class CalPointsImpl implements CalPoints{\n" +
                "    @Override\n" +
                "    public long calPoints(long points) {\n" +
                "        points = points*2;\n" +
                "        return points;\n" +
                "    }\n" +
                "}\n";

        List<Thread> threads = new ArrayList<>();
        for(int i=0;i<1;i++){
            Thread t = new Thread(()->{
                long start = System.currentTimeMillis();
                try {
                    run(code, 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("main:"+(System.currentTimeMillis()-start));
            });
            threads.add(t);
        }

        threads.stream().parallel().forEach(Thread::start);



    }

    public static Object run(String source, Object...args) throws Exception {
        // 声明类名
        String className = "CalPointsImpl";
        String packageName = "com.lry.basic.jvm.asm.transform_class.demo20";
        String prefix = String.format("package %s;", packageName);
        // 全类名：top.fomeiherz.Main
        String fullName = String.format("%s.%s", packageName, className);

        // 编译器
        JavaStringCompiler compiler = new JavaStringCompiler();
        long start = System.currentTimeMillis();

        Map<String, byte[]> results = compiler.compile(className + ".java", prefix + source);
        System.out.println(System.currentTimeMillis()-start);

        // 加载内存中byte到Class<?>对象
        Class<?> clazz = compiler.loadClass(fullName, results);
        // 创建实例
        Object instance = clazz.newInstance();
        Method method = clazz.getDeclaredMethod("calPoints",long.class);
        // String[]数组时必须使用Object[]封装
        // 否则会报错：java.lang.IllegalArgumentException: wrong number of arguments
        return method.invoke(instance, args);
    }
}
